package co.gov.medellin.ssti.sub.common.dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;

import co.gov.medellin.ssti.sub.common.PropertyReader;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;

/**
 * Clase utility para apoyar transacciones.
 * 
 * @author Consultsoft4
 * 
 */
public class TransactionUtil {
	/**
	 * Metodo que retorna una UserTransaction, para delimitar transacciones.
	 * 
	 * @return UserTransaction
	 */
	public static UserTransaction getUserTransaction() {
		Object obj = lookup("java:comp/UserTransaction");

		UserTransaction tx = (UserTransaction) narrow(obj,
				UserTransaction.class);

		return tx;
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	private static Object lookup(final String name) {
		Context ctx = getInitialContext();

		Object result = null;
		try {
			result = ctx.lookup(name);
			return result;
		} catch (NamingException ex) {
			throw new DAOException(ex);
		}
	}

	/**
	 * Metodo que retorna un initialContext.
	 * 
	 * @return initialContext
	 */
	public static Context getInitialContext() {
		Context ctx = null;

		try {
			// Solo usado para test unitarios.
			if (PropertyReader.getValue("stage").equalsIgnoreCase("TEST")) {
				ctx = new InitialContext();
				return (Context) ctx.lookup("java:/comp/env");
			}
			ctx = new InitialContext();
		} catch (NamingException ex) {
			throw new DAOException(ex);
		}
		return ctx;
	}

	/**
	 * 
	 * @param obj
	 * @param clase
	 * @return
	 */
	private static Object narrow(final Object obj, final Class<?> clase) {
		return javax.rmi.PortableRemoteObject.narrow(obj, clase);
	}
}
